package com.winning.pmph.ctrl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.winning.pmph.entity.*;
import com.winning.pmph.service.*;
import com.winning.pmph.utils.ApplicationContextUtil;
import com.winning.pmph.utils.KnowledgeEditUtil;
import com.winning.pmph.utils.UploadFileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wudi.andy@qq.com
 * @date 2020/10/19
 */
@Api(value = "知识接口")
@RestController
@RequestMapping("/pmph/action/knowledge")
public class KnowledgeCtrl {

    @Resource
    private KnowledgeService knowledgeService;
    @Resource
    private KnowledgeUnitService knowledgeUnitService;
    @Resource
    private ActivityItemService activityItemService;
    @Resource
    private ReleasedKnowledgeService releasedKnowledgeService;
    @Resource
    private TagService tagService;
    @Resource
    private RuleItemService ruleItemService;
    @Resource
    private ReleasedKnowledgeFieldService releasedKnowledgeFieldService;
    @Resource
    private PlatformService platformService;

    /**
     * 知识详情页面
     */
    @ApiOperation(value = "selectTempKnowledge", notes = "获取未发布知识详情页面接口")
    @GetMapping("selectTempKnowledge")
    public Knowledge selectTempKnowledge(String knowledgeId) {
        TempKnowledge tempKnowledge = knowledgeService.getTempKnowledgeAndFieldById(knowledgeId);
        tempKnowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        return tempKnowledge;
    }

    /**
     * 知识详情页面
     *
     * @throws IOException
     */
    @ApiOperation(value = "selectReleasedKnowledge", notes = "获取已发布知识详情页面接口")
    @GetMapping("selectReleasedKnowledge")
    public Knowledge selectReleasedKnowledge(String knowledgeId) {
        ReleasedKnowledge releasedKnowledge = knowledgeService.getReleasedKnowledgeAndFieldById(knowledgeId);
        releasedKnowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        return releasedKnowledge;
    }

    /**
     * 根据知识库, 查询知识列表;
     * 参数 name, knowledgeLibId, currentPage, pageSize;
     */
    @ApiOperation(value = "selectRelatedKnowledge", notes = "获取关联本知识库字段可选知识接口")
    @GetMapping("selectRelatedKnowledge")
    public Page<Knowledge> selectRelatedKnowledge(Knowledge knowledge) {
        Page<Knowledge> page = new Page<>(knowledge.getCurrentPage(), knowledge.getPageSize());
        LambdaQueryWrapper<Knowledge> queryWrapper = Wrappers.lambdaQuery(Knowledge.class);
        // 关联知识库;
        queryWrapper.eq(Knowledge::getKnowledgeLibId, knowledge.getKnowledgeLibId());
        // 名称过滤;
        queryWrapper.like(StringUtils.isNotBlank(knowledge.getName()), Knowledge::getName, knowledge.getName());
        return knowledgeService.page(page, queryWrapper);
    }

    /**
     * 知识编辑页面, 根据子任务获取知识(兼容新建)
     *
     * @param taskItem
     * @return
     */
    @ApiOperation(value = "selectKnowledgeByTaskItem", notes = "知识编辑页面, 根据子任务获取知识(兼容新建)")
    @PostMapping("selectKnowledgeByTaskItem")
    public Knowledge selectKnowledgeByTaskItem(@RequestBody TaskItem taskItem) {
        Knowledge knowledge = null;
        if (StringUtils.isNotEmpty(taskItem.getKnowledgeId())) {
            // 勘误, 查询released
            if (taskItem.getStatus() == TaskItem.STATUS_RELEASED){
                knowledge = knowledgeService.getReleasedKnowledgeAndFieldById(taskItem.getKnowledgeId());
            }
            else {
                knowledge = knowledgeService.getKnowledgeAndFieldById(taskItem.getKnowledgeId());
            }
        } else {
            knowledge = knowledgeService.createKnowledgeByLibId(taskItem.getKnowledgeLibId());
            knowledge.setName(taskItem.getName());
            knowledge.getKnowledgeFieldList().get(0).setProperty(taskItem.getName());
        }
        // 如果素材id不为空, 查询素材内容;
        if (StringUtils.isNotEmpty(knowledge.getKnowledgeUnitId())) {
            KnowledgeUnit knowledgeUnit = knowledgeUnitService.getBeanWithFieldById(knowledge.getKnowledgeUnitId());
            knowledge.setKnowledgeUnitName(knowledgeUnit.getName());
            knowledge.setKnowledgeUnitFieldList(knowledgeUnit.getKnowledgeUnitFieldList());
        }
        return knowledge;
    }

    /**
     * 编辑页面, 预览
     */
    @ApiOperation(value = "selectParse2Vo", notes = "编辑页面, 预览")
    @PostMapping("selectParse2Vo")
    public Knowledge selectParse2Vo(@RequestBody Knowledge knowledge) {
        knowledge.getKnowledgeFieldList().forEach(KnowledgeEditUtil::setFieldValue);
        return knowledge;
    }

    /**
     * 保存知识(兼容勘误)
     */
    @ApiOperation(value = "save", notes = "保存知识(兼容勘误)")
    @PostMapping("save")
    public void save(@RequestPart Knowledge knowledge, @RequestPart TaskItem taskItem) {
        if (taskItem.getStatus() == TaskItem.STATUS_RELEASED) {
            ReleasedKnowledge releasedKnowledge = JSON.parseObject(JSON.toJSONString(knowledge), ReleasedKnowledge.class);
            knowledgeService.correct(releasedKnowledge, taskItem);
        } else {
            TempKnowledge tempKnowledge = JSON.parseObject(JSON.toJSONString(knowledge), TempKnowledge.class);
            knowledgeService.save(tempKnowledge, taskItem);
        }
    }

    /**
     * 知识提交审核
     */
    @ApiOperation(value = "commit", notes = "识提交审核")
    @PostMapping("commit")
    public void commit(@RequestPart TempKnowledge knowledge, @RequestPart TaskItem taskItem) {
        knowledgeService.commit(knowledge, taskItem);
    }

    /**
     * 知识审核, 通过
     */

    @ApiOperation(value = "pass", notes = "知识编辑页面知识审核通过接口")
    @PostMapping("pass")
    public void pass(@RequestPart TempKnowledge knowledge, @RequestPart TaskItem taskItem) {
        knowledgeService.pass(knowledge, taskItem);

    }

    /**
     * 知识审核, 驳回
     *
     * @param knowledge
     * @param taskItem
     */
    @ApiOperation(value = "reject", notes = "知识编辑页面知识驳回接口")
    @PostMapping("reject")
    public void reject(@RequestPart TempKnowledge knowledge, @RequestPart TaskItem taskItem) {
        knowledgeService.reject(knowledge, taskItem);

    }

    @ApiOperation(value = "wordHtml", notes = "word 导入接口")
    @PostMapping("wordHtml")
    public boolean wordHtml(MultipartFile file, String taskId, String knowledgeLibId, String QuestionAnswerTaskId, String itemId) {
        String path = ApplicationContextUtil.BASE_DOWN_FORDER + "word/";
        String fileName = UploadFileUtil.uploadFile(file,
                path, false);
        String filePath = ApplicationContextUtil.BASE_DOWN_FORDER + "word/" + fileName;
        String name = StringUtils.substringBeforeLast(fileName, ".");
        boolean result = true;
        ActivityItem activityItem = new ActivityItem();
        activityItem.setManuscriptName(fileName);
        activityItem.setTaskId(taskId);
        activityItem.setKnowledgeLibId(knowledgeLibId);
        activityItem.setPath(filePath);
        try {
            knowledgeService.importTempKnowledge1(filePath, name, knowledgeLibId, taskId, QuestionAnswerTaskId);
            activityItem.setStatus(1);
            if (itemId != null) {
                activityItem.setId(itemId);
            }
        } catch (Exception e) {
            if (itemId != null) {
                activityItem.setId(itemId);
            }
            activityItem.setStatus(2);
            activityItem.setFailureReason(e.getMessage());
            e.printStackTrace();
            result = false;
            throw new RuntimeException(e.getMessage());
        } finally {
            activityItemService.saveOrUpdate(activityItem);

            return result;
        }
    }

    /**
     * 根据知识ID和知识字段ID查询正文，只有新媒体文章供稿库有
     *
     * @param knowledgeId
     * @return
     */
    @ApiOperation(value = "selectByKnowledgeId", notes = "查询135正文字段")
    @GetMapping("selectByKnowledgeId")
    public KnowledgeField selectByKnowledgeId(String knowledgeId) {
        return knowledgeService.selectByKnowledgeId(knowledgeId);
    }

    @ApiOperation(value = "updateFieldById", notes = "保存135编辑器内容")
    @PostMapping("updateFieldById")
    public void updateFieldById(@RequestBody TempKnowledgeField tempKnowledgeField) {
        knowledgeService.updateFieldById(tempKnowledgeField);
    }

    @ApiOperation(value = "selectReleasedKnowledgeDetail", notes = "根据知识ID查询知识详情(供外部调用)")
    @GetMapping("selectReleasedKnowledgeDetail")
    public Map<String, Object> selectReleasedKnowledgeDetail(String knowledgeId) {
        ReleasedKnowledge knowledge = releasedKnowledgeService.getById(knowledgeId);
        List<ReleasedKnowledgeField> releasedKnowledgeFieldList = releasedKnowledgeFieldService.lambdaQuery()
                .eq(ReleasedKnowledgeField::getKnowledgeId, knowledgeId).list();
        parseReleasedKnowledgeField(releasedKnowledgeFieldList);
        Map<String, Object> map = new HashMap<>();
        map.put("knowledge", knowledge);
        map.put("knowledgeFieldList", releasedKnowledgeFieldList);
        return map;
    }

    private void parseReleasedKnowledgeField(List<ReleasedKnowledgeField> fieldList) {
        fieldList.forEach((field) -> {
            if (field.getKind() == KnowledgeLibField.FIELD_KIND_REFERENCE) {
                String tagName = parseTagId2Name(field.getProperty());
                field.setProperty(tagName);
            } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPDOWNLIST) {
                String selectionName = parseDropdownValue2Name(field.getProperty());
                field.setProperty(selectionName);
            } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_DROPMULTILIST) {
                String selectionNames = parseMultiDropdownValues2Names(field.getProperty());
                field.setProperty(selectionNames);
            } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_ASSOCIATE_PLATFORM) {
                String platformNames = parsePlatformId2Names(field.getProperty());
                field.setProperty(platformNames);
            } else if (field.getKind() == KnowledgeLibField.FIELD_KIND_RICHEDITOR) {
                field.setProperty(field.getProperty());
                field.setProperty("");
            }
        });
    }

    private String parsePlatformId2Names(String property) {
        JSONArray array = JSONArray.parseArray(property);
        JSONArray nameArray = new JSONArray();
        for (Object object : array) {
            String id = (String) object;
            Platform platform = platformService.getById(id);
            nameArray.add(platform.getName());
        }
        return nameArray.toJSONString();
    }

    private String parseMultiDropdownValues2Names(String property) {
        JSONArray array = JSONArray.parseArray(property);
        JSONArray nameArray = new JSONArray();
        for (Object object : array) {
            String id = (String) object;
            RuleItem ruleItem = ruleItemService.getById(id);
            nameArray.add(ruleItem.getName());
        }
        return nameArray.toJSONString();
    }

    private String parseDropdownValue2Name(String property) {
        if (StringUtils.isBlank(property)) {
            return "";
        }
        RuleItem ruleItem = ruleItemService.getById(property);
        return ruleItem.getName();
    }

    private String parseTagId2Name(String property) {
        JSONArray array = JSONArray.parseArray(property);
        array.forEach((obj) -> {
            JSONArray subArray = (JSONArray) obj;
            int arrayLength = subArray.size();
            Tag tag = tagService.getById(subArray.getString(arrayLength - 1));
            subArray.clear();
            subArray.add(tag.getName());
        });
        return array.toJSONString();
    }
}
